﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using RCREEE.Library;
using RCREEE.Library.Entities;
using RCREEE.Web.Classes;

namespace RCREEE.Web
{
    public static class FieldsSet
    {
        public static string[] ContactName = new string[] { "lblContactName", "label15", "label17", "txtEditName", "Label46", "txtContactName_Insert" };
        public static string[] Field = new string[] { "label11", "label23", "label46", "ddlFieldEdit", "Label66", "ddlFieldInsert" };
        public static string[] PhoneNumber = new string[] { "label17", "label16", "label47", "txtPhoneNumber_Edit", "Label67", "TextBox1" };
        public static string[] FaxNumber = new string[] { "label24", "label12", "label49", "txtFaxNumber_Edit", "Label69", "txtFaxNumber_Insert" };
        public static string[] MobileNumber = new string[] { "label25", "label7", "label48", "txtMobileNumber_Edit", "Label68", "txtMobileNumber_Insert" };
        public static string[] Email = new string[] { "label26", "label3", "label50", "txtEmail_Edit", "Label70", "txtEmail_Insert" };
        public static string[] Website = new string[] { "label27", "label8", "label51", "txtWebsite_Edit", "Label71", "txtWebsite_Insert" };
        public static string[] Address = new string[] { "label28", "label14", "Label59", "txtAddress_Edit", "Label79", "txtAddress_Insert" };
        public static string[] Experience = new string[] { "label29", "label12", "Label57", "txtExperience_Edit", "Label77", "txtExperience_Insert" };
        //public static string[] PrentContact = new string[] { };
        public static string[] Description = new string[] { "label31", "label9", "Label56", "txtDescription_Edit", "Label76", "txtDescription_Insert" };
        //public static string[] Qualification = new string[] { };
        public static string[] Country = new string[] { "label33", "label4", "label44", "ddlCountries", "Label64", "ddlCountries" };
        public static string[] Category = new string[] { "label34", "label1", "label45", "ddlEntities", "Label65", "ddlEntities" };
        public static string[] QualificationLevel = new string[] { "label35", "label20", "Label53", "ddlQualificationLevelEdit", "Label73", "ddlQualificationLevelInsert" };
        public static string[] QualificationField = new string[] { "label36", "label21", "Label54", "ddlQualificationFieldEdit", "Label74", "ddlQualificationFieldInsert" };
        public static string[] QualificationSubField = new string[] { "label37", "label22", "Label55", "ddlQualificationSubFieldEdit", "Label75", "ddlQualificationSubFieldInsert" };
        public static string[] RenewableEnergy = new string[] { "", "chkIsRE", "", "chkIsRE_Edit", "", "chkIsRE_Insert" };
        public static string[] EnergyEfficiency = new string[] { "", "chkIsEE", "", "CheckBox1", "", "CheckBox1" };
        public static string[] NumberOfExperts = new string[] { "Label40", "label13", "Label58", "txtNumberOfExperts_Editv", "Label78", "txtNumberOfExperts_Insert" };
        public static string[] JobDescription = new string[] { "Label41", "label16", "Label60", "txtAffiliate_Edit", "Label80", "txtAffiliate_Insert" };
    }

    public enum ContactTypes
    {
        PersonalInformation,
        OfficesInformation,
        ResearchInstitutions,
        PrivateSectorCompanies,
        PublicEntities,
        EducationalInstitutions
    }

    public partial class Contact : System.Web.UI.Page
    {
        int eid_temp = 0;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (Request["E"] != null && Convert.ToString(Request["E"]) != "")
            // Get entity id form query string .. hold it into a hidden field
            {
                hiddenEntityId.Value = Convert.ToString(Request["E"]);
                Session["EID"] = Convert.ToString(Request["E"]);
            }
            // get record id from query string
            hiddenRecordId.Value = Convert.ToString(Request["R"]);

            // get CountryId
            int CountryId = 0;

            if (Request["C"] != null && Request["C"].ToString() != "")
                CountryId = Convert.ToInt32(Request["C"]);

            else if (Session["CountryId"] != null)
                CountryId = Convert.ToInt32(Session["CountryId"]);

            if (!Page.IsPostBack)
            {
                //// Add language Code to the current session
                //Session.Add("LanguageCode", 1033);

                DataTable dtAllContacts = new DataTable(); // private dataTable to hold all contacts
                DataTable dtAllItems = new DataTable();
                //DataTable dtPermissions = new DataTable();

                // check if Entity Id isn't passed through the query string
                if (hiddenEntityId.Value == "")
                {
                    // Show Warning label .. hide 
                    CheckEntityLabel.Text = "Please, Specify Entity category!";
                    ddlCountries.Visible = false;
                    MultiView1.Visible = false;
                }
                else
                {

                    // Get All Contacts for the current entity,language code & all countries
                    dtAllContacts = DataManager.GetAllMasterContacts(Convert.ToInt32(hiddenEntityId.Value), Convert.ToInt32(Session["LanguageCode"]), 0);
                    dtAllItems = DataManager.GetAllItems(Convert.ToInt32(Session["LanguageCode"]));

                    // add contacts datatable to the current session
                    Session.Add("dtAllContacts", dtAllContacts);
                    Session.Add("dtAllItems", dtAllItems);

                    #region Table Permissions
                    // Table declarations
                    //dtPermissions.Columns.Add("CountryId", typeof(int));
                    //dtPermissions.Columns.Add("CanAdd", typeof(bool));
                    //dtPermissions.Columns.Add("CanEdit", typeof(bool));
                    //dtPermissions.Columns.Add("CanDelete", typeof(bool));

                    //// New Row .. assigning permissions
                    //DataRow drPermission = dtPermissions.NewRow();
                    //drPermission["CountryId"] = 1;
                    //drPermission["CanAdd"] = true;
                    //drPermission["CanEdit"] = true;
                    //drPermission["CanDelete"] = true;

                    //dtPermissions.Rows.Add(drPermission);

                    //// Add table to the session object
                    //Session.Add("dtPermissions", dtPermissions);
                    #endregion

                }

            }
            //else
            //{
            //    HandleLanguageDDLVisibilty();
            //}

            ClearQueryString();

            if (hiddenRecordId.Value != "")
            {
                MultiView1.ActiveViewIndex = 0;
                ddlCountries.DataBind();
                ddlCountries.Items.FindByValue(Convert.ToString(DataManager.GetContactCountryId(Convert.ToInt32(hiddenRecordId.Value)))).Selected = true;
                gvMaster.DataBind();

                for (int i = 0; i < gvMaster.DataKeys.Count; i++)
                {
                    if (Convert.ToInt32(gvMaster.DataKeys[i].Value) == Convert.ToInt32(hiddenRecordId.Value))
                    {
                        gvMaster.SelectedIndex = i;
                        fvDetails.DataBind();
                        break;

                    }
                }
            }
            else if (CountryId != 0)
            {
                MultiView1.ActiveViewIndex = 0;
                ddlCountries.DataBind();
                ddlCountries.SelectedValue = CountryId.ToString();
                gvMaster.DataBind();
            }


            if (ddlCountries.SelectedValue != "" && ddlCountries.SelectedValue != "0" && !fvDetails.Visible)
                btnAddNew.Visible = Can("Add", Convert.ToInt32(ddlCountries.SelectedValue));
            else
                btnAddNew.Visible = false;

        }

        protected void Test1(object sender, EventArgs e)
        {
            //Response.RedirectLocation= "~/contact.aspx?E=" + Request["E"] + "&R=" + gvMaster.DataKeys[0].Value.ToString();
        }

        protected void ddlCountries_SelectedIndexChanged(object sender, EventArgs e)
        {

            // if All countries is selected
            if (ddlCountries.SelectedValue == "0")
            {
                ////Response.Redirect("Contact.aspx?E=" + hiddenEntityId.Value);
                //if (Page.IsPostBack)
                //    Response.Redirect("Contact.aspx?E=" + hiddenEntityId.Value);

                MultiView1.ActiveViewIndex = 1;
            }
            else
            // set "contact View" as the active view (Master gridView & Details FormView)
            {
                if (hiddenEntityId.Value != "")
                    RefreshAllContactsDataTable();

                MultiView1.ActiveViewIndex = 0;
                gvMaster.SelectedIndex = -1;
                fvDetails.DataBind();
            }

        }

        protected void contactRepeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (Session["dtAllContacts"] != null)

                // set  dataSource for Master GridView in each item
                if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
                {
                    // Get the current countryId
                    int currentCountryId = Convert.ToInt32(((HiddenField)e.Item.FindControl("hiddenCountryId")).Value);

                    // Select all contacts related to the current country from the dataTable
                    DataRow[] drResults = ((DataTable)Session["dtAllContacts"]).Select("CountryID = " + currentCountryId);

                    // Check if any contacts exist for the current country
                    if (drResults.Length > 0)
                    {
                        // Copy returned rows to a DataTable
                        DataTable results = drResults.CopyToDataTable();

                        // Set gridView DataSource
                        ((GridView)e.Item.FindControl("gvMaster")).DataSource = results;

                        // Bind gridView
                        ((GridView)e.Item.FindControl("gvMaster")).DataBind();
                    }
                }
        }

        protected void fvDetails_ItemUpdated(object sender, FormViewUpdatedEventArgs e)
        {
            if (Session["languageSessionParam"] != null)
                DetailsObjDataSource.SelectParameters["LanguageCode"] = (Parameter)Session["languageSessionParam"];

            // Update the main dataTable with the latest modifications
            RefreshAllContactsDataTable();

            // Rebind the master grid after update is completed to get latest data
            gvMaster.DataBind();
        }

        protected void fvDetails_ItemInserting(object sender, FormViewInsertEventArgs e)
        {
            if (ddlLanguage.SelectedValue != null || ddlLanguage.SelectedValue != "0")
                e.Values["LanguageCode"] = ddlLanguage.SelectedValue;
            else
                e.Values["LanguageCode"] = Convert.ToInt32(Session["LanguageCode"]);

            if (((TextBox)fvDetails.FindControl("txtExperience_Insert")).Text == "")
                e.Values["Experience"] = -1;

            if (((TextBox)fvDetails.FindControl("txtNumberOfExperts_Insert")).Text == "")
                e.Values["NumberOfExperts"] = -1;

            //e.Values["ParentContactId"] = ((DropDownList)fvDetails.FindControl("ddlParentContact_Insert")).SelectedValue;

            string parentContact = ((DropDownList)fvDetails.FindControl("ddlParentContact_Insert")).SelectedValue;

            if (parentContact == "")
                e.Values["ParentContactId"] = 0;
            else
                e.Values["ParentContactId"] = Convert.ToInt32(parentContact);
        }

        protected void fvDetails_ItemDeleting(object sender, FormViewDeleteEventArgs e)
        {
            // pass the current langusge code - which exists in the session- to the event arguments
            e.Values["LanguageCode"] = Convert.ToInt32(Session["LanguageCode"]);
        }

        protected void fvDetails_ItemDeleted(object sender, FormViewDeletedEventArgs e)
        {
            // Update the main dataTable with the latest modifications
            RefreshAllContactsDataTable();

            // Rebind the master grid after update is completed to get latest data
            gvMaster.DataBind();
        }

        protected void fvDetails_ItemInserted(object sender, FormViewInsertedEventArgs e)
        {
            if (Session["languageSessionParam"] != null)
                DetailsObjDataSource.SelectParameters["LanguageCode"] = (Parameter)Session["languageSessionParam"];

            // Update the main dataTable with the latest modifications
            RefreshAllContactsDataTable();

            gvMaster.DataSource = null;

            // Rebind the master grid after update is completed to get latest data
            gvMaster.DataBind();
        }

        private void SetFieldVisibility(
           string[] Fields,
            bool Visibility)
        {
            if (fvDetails.CurrentMode == FormViewMode.Edit)
            {
                if (Fields[2] != "" && (fvDetails.FindControl(Fields[2])) != null)
                    (fvDetails.FindControl(Fields[2])).Visible = Visibility;
                if (Fields[3] != "" && (fvDetails.FindControl(Fields[3])) != null)
                    (fvDetails.FindControl(Fields[3])).Visible = Visibility;
            }
            else if (fvDetails.CurrentMode == FormViewMode.ReadOnly && gvMaster.SelectedIndex != -1)
            {
                if (Fields[0] != "" && (fvDetails.FindControl(Fields[0]))!= null)
                    (fvDetails.FindControl(Fields[0])).Visible = Visibility;
                if (Fields[1] != "" && (fvDetails.FindControl(Fields[1])) != null)
                    (fvDetails.FindControl(Fields[1])).Visible = Visibility;
            }
            else if (fvDetails.CurrentMode == FormViewMode.Insert)
            {
                if (Fields[4] != "" && (fvDetails.FindControl(Fields[4])) != null)
                    (fvDetails.FindControl(Fields[4])).Visible = Visibility;
                if (Fields[5] != "" && (fvDetails.FindControl(Fields[5]))!= null)
                    (fvDetails.FindControl(Fields[5])).Visible = Visibility;
            }
        }

        public void HideAllContactsFields()
        {
            SetFieldVisibility(FieldsSet.ContactName, false);
            SetFieldVisibility(FieldsSet.Field, false);
            SetFieldVisibility(FieldsSet.PhoneNumber, false);
            SetFieldVisibility(FieldsSet.FaxNumber, false);
            SetFieldVisibility(FieldsSet.MobileNumber, false);
            SetFieldVisibility(FieldsSet.Email, false);
            SetFieldVisibility(FieldsSet.Website, false);
            SetFieldVisibility(FieldsSet.Address, false);
            SetFieldVisibility(FieldsSet.Experience, false);

            SetFieldVisibility(FieldsSet.Description, false);

            //SetFieldVisibility(FieldsSet.Country, false);
            //SetFieldVisibility(FieldsSet.Category, false);
            SetFieldVisibility(FieldsSet.QualificationLevel, false);
            SetFieldVisibility(FieldsSet.QualificationField, false);
            SetFieldVisibility(FieldsSet.QualificationSubField, false);
            SetFieldVisibility(FieldsSet.RenewableEnergy, false);
            SetFieldVisibility(FieldsSet.EnergyEfficiency, false);
            SetFieldVisibility(FieldsSet.NumberOfExperts, false);
            SetFieldVisibility(FieldsSet.JobDescription, false);

        }

        public void SetTypeFieldsVisibility(ContactTypes Type)
        {

            if (Type == ContactTypes.PersonalInformation)
            {
                HideAllContactsFields();

                SetFieldVisibility(FieldsSet.ContactName, true); //Name
                SetFieldVisibility(FieldsSet.Field, true); //Speciality
                SetFieldVisibility(FieldsSet.PhoneNumber, true); //Office phone number
                SetFieldVisibility(FieldsSet.FaxNumber, true);  //Fax
                SetFieldVisibility(FieldsSet.Email, true);  //Email Address
                SetFieldVisibility(FieldsSet.QualificationLevel, true); //Degree
                SetFieldVisibility(FieldsSet.Experience, true); //Years of experience
                SetFieldVisibility(FieldsSet.JobDescription, true); // Position
            }
            else
                if (Type == ContactTypes.OfficesInformation)
                {
                    HideAllContactsFields();

                    SetFieldVisibility(FieldsSet.ContactName, true); //Name
                    SetFieldVisibility(FieldsSet.Address, true); //Address
                    SetFieldVisibility(FieldsSet.PhoneNumber, true); //Office phone number
                    SetFieldVisibility(FieldsSet.FaxNumber, true); //Fax
                    SetFieldVisibility(FieldsSet.Email, true); //Email address
                    SetFieldVisibility(FieldsSet.Website, true); //Website
                    SetFieldVisibility(FieldsSet.Field, true); //Field of Work
                    SetFieldVisibility(FieldsSet.Experience, true); //Years of experience
                    SetFieldVisibility(FieldsSet.NumberOfExperts, true); //Number  of Experts
                }
                else
                    if (Type == ContactTypes.ResearchInstitutions)
                    {
                        HideAllContactsFields();

                        SetFieldVisibility(FieldsSet.ContactName, true); //Name
                        SetFieldVisibility(FieldsSet.Address, true); //Address
                        SetFieldVisibility(FieldsSet.PhoneNumber, true); //Tel
                        SetFieldVisibility(FieldsSet.FaxNumber, true); //Fax
                        SetFieldVisibility(FieldsSet.Email, true); //email
                        SetFieldVisibility(FieldsSet.Website, true); //Website
                        SetFieldVisibility(FieldsSet.Field, true); //Speciality
                    }
                    else
                        if (Type == ContactTypes.PrivateSectorCompanies)
                        {
                            HideAllContactsFields();

                            SetFieldVisibility(FieldsSet.ContactName, true); //Name
                            SetFieldVisibility(FieldsSet.Address, true); //Address
                            SetFieldVisibility(FieldsSet.PhoneNumber, true); //Tel
                            SetFieldVisibility(FieldsSet.MobileNumber, true); //Mobile
                            SetFieldVisibility(FieldsSet.FaxNumber, true); //Fax
                            SetFieldVisibility(FieldsSet.Email, true); //email
                            SetFieldVisibility(FieldsSet.Website, true); //Website
                            SetFieldVisibility(FieldsSet.Field, true); //Field Of Work
                            SetFieldVisibility(FieldsSet.Experience, true); //Years of expertise
                        }
                        else
                            if (Type == ContactTypes.PublicEntities)
                            {
                                HideAllContactsFields();

                                SetFieldVisibility(FieldsSet.ContactName, true); //Responsible Intity
                                SetFieldVisibility(FieldsSet.Address, true); //Address
                                SetFieldVisibility(FieldsSet.PhoneNumber, true); //Tel

                                SetFieldVisibility(FieldsSet.FaxNumber, true); //Fax
                                SetFieldVisibility(FieldsSet.Email, true); //email
                                SetFieldVisibility(FieldsSet.Website, true); //Website
                            }
                            else
                                if (Type == ContactTypes.EducationalInstitutions)
                                {
                                    HideAllContactsFields();

                                    SetFieldVisibility(FieldsSet.ContactName, true); //Name
                                    SetFieldVisibility(FieldsSet.Address, true); //Address
                                    SetFieldVisibility(FieldsSet.PhoneNumber, true); //Tel

                                    SetFieldVisibility(FieldsSet.FaxNumber, true); //Fax
                                    SetFieldVisibility(FieldsSet.Email, true); //email
                                    SetFieldVisibility(FieldsSet.Website, true); //Website
                                    SetFieldVisibility(FieldsSet.Field, true); //Speciality

                                }
        }

        protected void fvDetails_DataBound(object sender, EventArgs e)
        {

            try
            {
                if (fvDetails.CurrentMode == FormViewMode.Edit)
                {
                    if (((Label)fvDetails.FindControl("lblHiddenParentContactCountryId")).Text != "")
                        ((DropDownList)fvDetails.FindControl("ddlParentContactCountry")).SelectedValue = ((Label)fvDetails.FindControl("lblHiddenParentContactCountryId")).Text;

                    if (((Label)fvDetails.FindControl("lblHiddenParentContactEntityId")).Text != "")
                        ((DropDownList)fvDetails.FindControl("ddlParentContactEntity")).SelectedValue = ((Label)fvDetails.FindControl("lblHiddenParentContactEntityId")).Text;

                    hiddenParentEntityId.Value = ((DropDownList)fvDetails.FindControl("ddlParentContactEntity")).SelectedValue;
                    hiddenParentCountryId.Value = ((DropDownList)fvDetails.FindControl("ddlParentContactCountry")).SelectedValue;
                    ((DropDownList)fvDetails.FindControl("ddlParentContact")).DataBind();

                    // pass the parentcontactId as the selected value for ddlParentContact
                    ((DropDownList)fvDetails.FindControl("ddlParentContact")).SelectedValue = ((Label)fvDetails.FindControl("hiddenLabelParentContactID")).Text;

                    ddlLanguage.SelectedValue = ((Label)fvDetails.FindControl("lblLanguageCode")).Text;

                }
                else if (fvDetails.CurrentMode == FormViewMode.Insert)
                {
                    hiddenParentEntityId.Value = ((DropDownList)fvDetails.FindControl("ddlParentContactEntity_Insert")).SelectedValue;
                    hiddenParentCountryId.Value = ((DropDownList)fvDetails.FindControl("ddlParentContactCountry_Insert")).SelectedValue;
                    ((DropDownList)fvDetails.FindControl("ddlParentContact_Insert")).DataBind();

                    ((DropDownList)fvDetails.FindControl("ddlCountries")).SelectedValue = ddlCountries.SelectedValue;
                    ((DropDownList)fvDetails.FindControl("ddlCountries")).Enabled = false;

                    ((DropDownList)fvDetails.FindControl("ddlEntities")).SelectedValue = hiddenEntityId.Value;
                    ((DropDownList)fvDetails.FindControl("ddlEntities")).Enabled = false;
                }
                else if (fvDetails.CurrentMode == FormViewMode.ReadOnly)
                {

                    if (ddlCountries.SelectedValue != "0")
                    {
                        try
                        {
                            ((Button)(fvDetails.FindControl("EditButton"))).Visible = Can("Update", Convert.ToInt32(ddlCountries.SelectedValue));
                            ((Button)(fvDetails.FindControl("DeleteButton"))).Visible = Can("Delete", Convert.ToInt32(ddlCountries.SelectedValue));
                            ((Button)(fvDetails.FindControl("NewButton"))).Visible = Can("Add", Convert.ToInt32(ddlCountries.SelectedValue));
                        }
                        catch (Exception exp)
                        { }
                    }
                }
            }
            catch (Exception exp)
            {

            }
            //DetailsPanel.Width = Unit.Pixel((int)(fvDetails.Width.Value + Unit.Pixel(5).Value));
            if (gvMaster.SelectedValue == null || gvMaster.SelectedIndex == -1)
                btnAddNew.Visible = Can("Add", Convert.ToInt32(ddlCountries.SelectedValue));
            else if (Can("Add", Convert.ToInt32(ddlCountries.SelectedValue)))
            {
                btnAddNew.Visible = !fvDetails.Visible;
            }

            //HandleLanguageDDLVisibilty();

            switch (Convert.ToInt32(hiddenEntityId.Value))
            {
                case 514:
                case 561:
                case 563:
                    SetTypeFieldsVisibility(ContactTypes.PublicEntities);
                    break;

                case 524:
                case 526:
                    SetTypeFieldsVisibility(ContactTypes.OfficesInformation);
                    break;

                case 530:
                    SetTypeFieldsVisibility(ContactTypes.ResearchInstitutions);
                    break;

                case 536:
                    SetTypeFieldsVisibility(ContactTypes.EducationalInstitutions);
                    break;

                case 552:
                case 554:
                    SetTypeFieldsVisibility(ContactTypes.PrivateSectorCompanies);
                    break;
            }
        }

        protected void fvDetails_ItemUpdating(object sender, FormViewUpdateEventArgs e)
        {
            if (((DropDownList)fvDetails.FindControl("ddlParentContact")).SelectedValue != "")
                e.NewValues["ParentContactId"] = ((DropDownList)fvDetails.FindControl("ddlParentContact")).SelectedValue;
            else
                e.NewValues["ParentContactId"] = null;

            if (ddlLanguage.SelectedValue != null || ddlLanguage.SelectedValue != "0")
                e.NewValues["LanguageCode"] = ddlLanguage.SelectedValue;
            else
                e.NewValues["LanguageCode"] = Convert.ToInt32(Session["LanguageCode"]);

            if (((TextBox)fvDetails.FindControl("txtExperience_Edit")).Text == "")
                e.NewValues["Experience"] = -1;

            if (((TextBox)fvDetails.FindControl("txtNumberOfExperts_Edit")).Text == "")
                e.NewValues["NumberOfExperts"] = -1;
        }

        protected void ContactView_Activate(object sender, EventArgs e)
        {
            gvMaster.DataBind();
        }

        protected void AllContactsView_Activate(object sender, EventArgs e)
        {
            contactRepeater.DataBind();
        }

        /// <summary>
        /// Refresh the DataTable that has the main data with the latest updates
        /// </summary>
        private void RefreshAllContactsDataTable()
        {
            DataTable dtAllContact = new DataTable();
            dtAllContact = DataManager.GetAllMasterContacts(Convert.ToInt32(hiddenEntityId.Value), Convert.ToInt32(Session["LanguageCode"]), 0);
            Session.Remove("dtAllContacts");
            Session.Add("dtAllContacts", dtAllContact);
        }

        /// <summary>
        /// Refresh the DataTable that has the all Items, and replace it in the session object
        /// </summary>
        private void RefreshAllItemsDataTable()
        {
            DataTable dtAllItems = new DataTable();
            dtAllItems = DataManager.GetAllItems(Convert.ToInt32(Session["LanguageCode"]));
            Session.Remove("dtAllItems");
            Session.Add("dtAllItems", dtAllItems);
        }

        private List<TinyItem> GetAvailableParentContact(int CurrentContactId, int CountryId, int EntityId, int LanguageCode)
        {
            return DataManager.GetAvailableParentContacts(CurrentContactId, CountryId, EntityId, LanguageCode);
        }

        protected void ddlParentContactCountry_SelectedIndexChanged(object sender, EventArgs e)
        {
            hiddenParentCountryId.Value = ((DropDownList)fvDetails.FindControl("ddlParentContactCountry")).SelectedValue;
            hiddenParentEntityId.Value = ((DropDownList)fvDetails.FindControl("ddlParentContactEntity")).SelectedValue;
            ((DropDownList)fvDetails.FindControl("ddlParentContact")).DataBind();
        }

        protected void fvDetails_Load(object sender, EventArgs e)
        {
            try
            {
                if (fvDetails.CurrentMode == FormViewMode.Edit || fvDetails.CurrentMode == FormViewMode.Insert)
                {
                    //divLanguageDDL.Visible = true;
                }
                else
                {
                    if (hiddenRecordId.Value != "")
                    {
                        ((GridView)fvDetails.FindControl("gvRelatedContacts")).DataSource = DataManager.GetRelatedContacts(Convert.ToInt32(hiddenRecordId.Value), Convert.ToInt32(Session["LanguageCode"]));
                        ((GridView)fvDetails.FindControl("gvRelatedContacts")).DataBind();

                        ((GridView)fvDetails.FindControl("gvRelatedProjects")).DataSource = DataManager.GetRelatedProjects(Convert.ToInt32(hiddenRecordId.Value), Convert.ToInt32(Session["LanguageCode"]));
                        ((GridView)fvDetails.FindControl("gvRelatedProjects")).DataBind();
                    }
                    //divLanguageDDL.Visible = false;

                }

            }
            catch (Exception exc) { }

        }

        protected void ddlParentContactEntity_SelectedIndexChanged(object sender, EventArgs e)
        {
            hiddenParentEntityId.Value = ((DropDownList)fvDetails.FindControl("ddlParentContactEntity")).SelectedValue;
            hiddenParentCountryId.Value = ((DropDownList)fvDetails.FindControl("ddlParentContactCountry")).SelectedValue;
            ((DropDownList)fvDetails.FindControl("ddlParentContact")).DataBind();
        }

        protected void ddlParentContactCountry_Insert_SelectedIndexChanged(object sender, EventArgs e)
        {
            hiddenParentCountryId.Value = ((DropDownList)fvDetails.FindControl("ddlParentContactCountry_Insert")).SelectedValue;
            hiddenParentEntityId.Value = ((DropDownList)fvDetails.FindControl("ddlParentContactEntity_Insert")).SelectedValue;
            ((DropDownList)fvDetails.FindControl("ddlParentContact_Insert")).DataBind();
        }

        protected void ddlParentContactEntity_Insert_SelectedIndexChanged(object sender, EventArgs e)
        {
            hiddenParentEntityId.Value = ((DropDownList)fvDetails.FindControl("ddlParentContactEntity_Insert")).SelectedValue;
            hiddenParentCountryId.Value = ((DropDownList)fvDetails.FindControl("ddlParentContactCountry_Insert")).SelectedValue;
            ((DropDownList)fvDetails.FindControl("ddlParentContact_Insert")).DataBind();
        }

        public DataTable GetAllCategoryItems(int CategoryId)
        {
            if (Session["dtAllItems"] == null)
                RefreshAllItemsDataTable();

            DataTable dtCategoryItems = ((DataTable)Session["dtAllItems"]).Clone();

            DataRow[] drCategoryItems = ((DataTable)Session["dtAllItems"]).Select("CategoryId =" + CategoryId);



            if (drCategoryItems.Length > 0)
                dtCategoryItems = drCategoryItems.CopyToDataTable();

            DataRow drEmpty = dtCategoryItems.NewRow();
            drEmpty["ItemId"] = 0;
            drEmpty["ItemName"] = "";
            dtCategoryItems.Rows.InsertAt(drEmpty, 0);

            return dtCategoryItems;
        }

        public DataTable GetAllCategoryItems(int CategoryId, string paramParentItemId)
        {
            try
            {
                if (Session["dtAllItems"] == null)
                    RefreshAllItemsDataTable();

                DataTable dtCategoryItems = ((DataTable)Session["dtAllItems"]).Clone();

                int ParentItemId = 0;

                ParentItemId = !String.IsNullOrEmpty(paramParentItemId) ? Convert.ToInt32(paramParentItemId) : 0;
                
                if (ParentItemId == 0 && Session["EID"] != null)
                    ParentItemId = Convert.ToInt32(Session["EID"]);

                if (ParentItemId == 0 && hiddenEntityId != null)
                    ParentItemId = !String.IsNullOrEmpty(hiddenEntityId.Value) ? Convert.ToInt32(hiddenEntityId.Value) : 0;

                if (ParentItemId == 0)
                    ParentItemId = !String.IsNullOrEmpty(Request["E"]) ? Convert.ToInt32(Request["E"]) : 0;

                DataRow[] drCategoryItems = ((DataTable)Session["dtAllItems"]).Select("CategoryId =" + CategoryId + " AND ParentItemId = " + ParentItemId);



                if (drCategoryItems.Length > 0)
                    dtCategoryItems = drCategoryItems.CopyToDataTable();

                DataRow drEmpty = dtCategoryItems.NewRow();
                drEmpty["ItemId"] = 0;
                drEmpty["ItemName"] = "";
                dtCategoryItems.Rows.InsertAt(drEmpty, 0);

                return dtCategoryItems;
            }
            catch (Exception exc)
            {
                return null;
            }
        }



        protected void btnAddNew_Click(object sender, EventArgs e)
        {
            gvMaster.SelectedIndex = -1;
            fvDetails.ChangeMode(FormViewMode.Insert);

            // Show Language DropDownList
            lblLanguage.Visible = true;
            ddlLanguage.Visible = true;
        }

        protected void fvDetails_ModeChanging(object sender, FormViewModeEventArgs e)
        {
            if (e.CancelingEdit)
            {
                btnAddNew.Visible = Can("Add", Convert.ToInt32(ddlCountries.SelectedValue));

                if (Session["languageSessionParam"] != null)
                    DetailsObjDataSource.SelectParameters["LanguageCode"] = (Parameter)Session["languageSessionParam"];
            }
            //if (e.NewMode == FormViewMode.ReadOnly)
            //divLanguageDDL.Visible = false;
            //divLanguageDDL.Attributes.Add("style", "visibility:hiddden");
            //ddlLanguage.Visible = false;
            //ClientScript.RegisterClientScriptBlock(ClientScript.GetType(),"HideControl", "document.getElementById(\"divLanguageDDL\").style.visibility=\"hidden\";");
            //Page.RegisterClientScriptBlock("HideControl", "document.getElementById(\"divLanguageDDL\").style.visibility=\"hidden\";");
            //else
            //divLanguageDDL.Attributes.Add("style", "visibility:Visible");
            //divLanguageDDL.Visible = true;
            //ddlLanguage.Visible = true;
            //ClientScript.RegisterClientScriptBlock(ClientScript.GetType(), "HideControl", "document.getElementById(\"divLanguageDDL\").style.visibility=\"visible\";");
            //HandleLanguageDDLVisibilty();
        }

        public void ClearQueryString()
        {
            string clientCommand = string.Format("document.forms[\"{0}\"].action = \"{1}\";",
            this.Form.Name, Request.Url.Segments[Request.Url.Segments.Length - 1]);

            ClientScript.RegisterStartupScript(this.GetType(), "qr", clientCommand, true);
        }

        public bool Can(string permission, int CountryId)
        {
            //if (Session["dtPermissions"] == null)
            //{
            //    #region Table Permissions
            //    // Table declarations
            //    DataTable dtPermissions = new DataTable();

            //    dtPermissions.Columns.Add("CountryId", typeof(int));
            //    dtPermissions.Columns.Add("CanAdd", typeof(bool));
            //    dtPermissions.Columns.Add("CanEdit", typeof(bool));
            //    dtPermissions.Columns.Add("CanDelete", typeof(bool));

            //    // New Row .. assigning permissions
            //    DataRow drPermission = dtPermissions.NewRow();
            //    drPermission["CountryId"] = 1;
            //    drPermission["CanAdd"] = true;
            //    drPermission["CanEdit"] = true;
            //    drPermission["CanDelete"] = true;

            //    dtPermissions.Rows.Add(drPermission);

            //    Session.Remove("dtPermissions");

            //    // Add table to the session object
            //    Session.Add("dtPermissions", dtPermissions);
            //    #endregion
            //}

            try
            {
                DataRow[] dr = ((DataTable)Session["Permissions"]).Select("CountryId = " + CountryId.ToString());

                if (dr.Length > 0)
                {
                    return Convert.ToBoolean(dr[0]["Can" + permission]);
                }
                else
                    return false;
            }
            catch (Exception exc)
            {
                return false;
            }
        }

        protected void ddlLanguage_SelectedIndexChanged(object sender, EventArgs e)
        {
            Parameter sessionParam = DetailsObjDataSource.SelectParameters["LanguageCode"];
            Session.Remove("languageSessionParam");
            Session.Add("languageSessionParam", sessionParam);

            Parameter currentLanguageParam = new Parameter("LanguageCode", DbType.Int32, ddlLanguage.SelectedValue);
            DetailsObjDataSource.SelectParameters["LanguageCode"] = currentLanguageParam;
            fvDetails.DataBind();
        }

        protected void fvDetails_ModeChanged(object sender, EventArgs e)
        {
            if (fvDetails.CurrentMode == FormViewMode.ReadOnly)
            {
                lblLanguage.Visible = false;
                ddlLanguage.Visible = false;
            }
            else
            {
                lblLanguage.Visible = true;
                ddlLanguage.Visible = true;

                if (fvDetails.CurrentMode == FormViewMode.Insert)
                {
                    try
                    {
                        ((DropDownList)fvDetails.FindControl("ddlCountries")).SelectedValue = ddlCountries.SelectedValue;
                        ((DropDownList)fvDetails.FindControl("ddlEntities")).SelectedValue = hiddenEntityId.Value;
                    }
                    catch (Exception)
                    { }
                }
            }
        }

        protected void fvDetails_DataBinding(object sender, EventArgs e)
        {
        }



        protected void Button1_Click(object sender, EventArgs e)
        {
            List<string> validColumns = new List<string> { "ContactName", "FieldName", "FieldName", "FaxNumber", "Email" };
            var dataTable = DataManager.GetAllMasterContacts(Convert.ToInt32(hiddenEntityId.Value), Convert.ToInt32(Session["LanguageCode"]), 0);
            ExportToExcel(dataTable, validColumns);
        }

        private void ExportToExcel(DataTable dataTable, List<string> validColumns)
        {
            try
            {

                GridView gridView = Helper.ExportToExcel(dataTable, validColumns);


                Response.Clear();

                Response.AddHeader("content-disposition", "attachment; filename=\"Product Numbers Generated on (" + DateTime.Now.Date.ToString("d MMM yyyy") + ").xls\"");

                Response.Charset = "";

                // If you want the option to open the Excel file without saving than

                // comment out the line below

                Response.Cache.SetCacheability(HttpCacheability.NoCache);

                Response.ContentType = "application/vnd.xls";

                System.IO.StringWriter stringWrite = new System.IO.StringWriter();

                System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);

                gridView.RenderControl(htmlWrite);

                Response.Write(stringWrite.ToString());

                Response.End();
            }
            catch (Exception exc)
            {
                throw exc;
            }
        }
    }
    //public class AddTemplateToGridView : ITemplate
    //{
    //    ListItemType _type;
    //    string _colName;

    //    public AddTemplateToGridView(ListItemType type, string colname)
    //    {
    //        _type = type;

    //        _colName = colname;

    //    }
    //    void ITemplate.InstantiateIn(System.Web.UI.Control container)
    //    {

    //        switch (_type)
    //        {
    //            case ListItemType.Item:

    //                HyperLink ht = new HyperLink();
    //                ht.Target = "_blank";
    //                ht.DataBinding += new EventHandler(ht_DataBinding);
    //                container.Controls.Add(ht);

    //                break;
    //        }

    //    }

    //    void ht_DataBinding(object sender, EventArgs e)
    //    {

    //        HyperLink lnk = (HyperLink)sender;
    //        GridViewRow container = (GridViewRow)lnk.NamingContainer;
    //        object dataValue = DataBinder.Eval(container.DataItem, _colName);
    //        if (dataValue != DBNull.Value)
    //        {
    //            lnk.Text = dataValue.ToString();
    //            lnk.NavigateUrl = "http://www.booktitles.com";
    //        }

    //    }
    //}
}
